package com.edu.web.controller.info;

import cn.hutool.core.util.StrUtil;
import com.edu.common.exception.ServiceException;
import com.edu.common.utils.poi.ExcelReaderUtil;
import com.edu.framework.config.ServerConfig;
import com.edu.framework.websocket.service.ExamSeatService;
import com.edu.system.service.ITPublishClassService;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.edu.common.annotation.Log;
import com.edu.common.core.controller.BaseController;
import com.edu.common.core.domain.AjaxResult;
import com.edu.common.enums.BusinessType;
import com.edu.system.domain.TExamSeat;
import com.edu.system.service.ITExamSeatService;
import com.edu.common.utils.poi.ExcelUtil;
import com.edu.common.core.page.TableDataInfo;

/**
 * 座位图Controller
 * 
 * @author xxxx
 * @date 2023-12-31
 */
@Slf4j
@RestController
@RequestMapping("/system/seat")
public class

TExamSeatController extends BaseController
{
    @Autowired
    private ITExamSeatService tExamSeatService;
    @Resource
    private ExamSeatService wsExamSeatService;
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询座位图列表
     */
    @PreAuthorize("@ss.hasPermi('system:seat:list')")
    @GetMapping("/list")
    public TableDataInfo list(TExamSeat tExamSeat)
    {
        startPage();
        List<TExamSeat> list = tExamSeatService.showExamSeatList(tExamSeat);
        return getDataTable(list);
    }

    /**
     * 导出座位图列表
     */
    @PreAuthorize("@ss.hasPermi('system:seat:export')")
    @Log(title = "座位图", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TExamSeat tExamSeat)
    {
        List<TExamSeat> list = tExamSeatService.showExamSeatList(tExamSeat);
        ExcelUtil<TExamSeat> util = new ExcelUtil<TExamSeat>(TExamSeat.class);
        util.exportExcel(response, list, "座位图数据");
    }

    /**
     * 获取座位图详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:seat:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tExamSeatService.selectTExamSeatById(id));
    }

    /**
     * 新增座位图
     */
    @PreAuthorize("@ss.hasPermi('system:seat:add')")
    @Log(title = "座位图", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TExamSeat tExamSeat)
    {
        if (StrUtil.isBlank(tExamSeat.getFileUrl())){
            throw new ServiceException("请上传座位图excel");
        }
        int i = tExamSeatService.insertTExamSeat(tExamSeat);
        CompletableFuture.runAsync(() -> wsExamSeatService.pushMsg(new ArrayList<>()));
        return toAjax(i);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<TExamSeat> util = new ExcelUtil<TExamSeat>(TExamSeat.class);
        util.importTemplateExcel(response, "导入座位图");
    }


    /**
     * 修改座位图
     */
    @PreAuthorize("@ss.hasPermi('system:seat:edit')")
    @Log(title = "座位图", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TExamSeat tExamSeat)
    {
        log.info("座位图fileUrl:{}", tExamSeat.getFileUrl());
        List<List<String>> lists = null;
        if (StrUtil.isNotBlank(tExamSeat.getFileUrl())){
            Map<String, List<List<String>>> roomMap = Optional.ofNullable(tExamSeat.getFileUrl())
                .filter(StrUtil::isNotBlank)
                .map(a -> ExcelReaderUtil.readExcelFromUrl(tExamSeat.getFileUrl()))
                .orElseGet(() -> null);
            lists = roomMap.entrySet().stream().findFirst().get().getValue();
        }

        int i = tExamSeatService.updateTExamSeat(tExamSeat, lists);
        CompletableFuture.runAsync(() -> wsExamSeatService.pushMsg(new ArrayList<>()));
        return toAjax(i);
    }

    /**
     * 删除座位图
     */
    @PreAuthorize("@ss.hasPermi('system:seat:remove')")
    @Log(title = "座位图", businessType = BusinessType.DELETE)
	  @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        int i = tExamSeatService.deleteTExamSeatByIds(ids);
        CompletableFuture.runAsync(() -> wsExamSeatService.pushMsg(new ArrayList<>()));
        return toAjax(i);
    }

    /**
     * 下发消息
     * 异步
     * @param seatIds
     */
    private void pushMsg(List<Long> seatIds, boolean isCheckDouble) {
        List<Long> before = tExamSeatService.queryClassIdsByIds(seatIds);
        CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                log.error("睡眠异常");
            }
            if (isCheckDouble){
                List<Long> after = tExamSeatService.queryClassIdsByIds(seatIds);
                before.addAll(after);
            }
            wsExamSeatService.buildTrigger(before);
        });
    }
}
